
const glob = require('glob')
const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const merge = require('webpack-merge')
const common = require('./webpack.common.js')

// 不同浏览器存放cookie的对象
const cookieMap = {}
// 去掉域名的sso登录地址  
// const ssoUrl = '/Search/Home/HomePage/?value=backLogin&w=&returnurl=/buy"
// 默认打开页，为空时写'/'
const openPage = '/activity'
let accesstoken = '';

const intputDirectory = path.resolve(__dirname, 'src/view')
const outputDirectory = path.resolve(__dirname, 'activity')


// 多页面打包
const setMPA = () => {
  const entry = {};
  entry.vendor=['vue', 'vue-router', 'vuex', 'axios']
  const htmlWebpackPlugins = [];

  const entryFiles = glob.sync(path.join(__dirname, './src/view/*/index.js'))

  Object.keys(entryFiles).map(index => {
      const entryFile = entryFiles[index];
      const match = entryFile.match(/src\/view\/(.*)\/index\.js/);
      const pageName = match && match[1];

      entry[pageName] = entryFile;
      htmlWebpackPlugins.push(
          new HtmlWebpackPlugin({
              template: path.join(__dirname, `src/view/${pageName}/index.html`),
              filename: `${pageName}.html`,
              chunks: [pageName],
              inject: true,
              minify: {
                  html5: true,
                  collapseWhitespace: true,
                  preserveLineBreaks: false,
                  minifyCSS: true,
                  minifyJS: true,
                  removeComments: false
              }
          })
      );
  })
  console.log('entryFiles', entryFiles);

  return {
      entry,
      htmlWebpackPlugins
  }
}

const { entry, htmlWebpackPlugins } = setMPA();
module.exports = merge(common, {
  mode: 'development',
  devtool: 'eval-source-map',
  entry,
  // vendor: ['vue', 'vue-router', 'vuex', 'axios'],
  // entry: {
  //   winterMobile: path.resolve(intputDirectory + "/singlePage/", 'index.js'),
  //   main: path.resolve(intputDirectory + "/index/", 'index.js'),
  //   vendor: ['vue', 'vue-router', 'vuex', 'axios']
  // },
  output: {
    publicPath: '/',
    path: outputDirectory,
    filename: 'js/[name]-[hash:8].js'
  },
  devServer: {
    disableHostCheck: true,
    // openPage: './src/view/singlePage/singlePage.html',
    overlay: true,
    index: '',
    historyApiFallback: true,
    hot: true,
    host: "192.168.50.179",
    inline: true,
    progress: true,
    open: true,
    port: 6060,
    // https: true,
    proxy: [{
        context: ['/api', '/ssoapi', '/ismsapi','/teammanageapi'],
        // context: ['/teammanageapi'],
        target: 'https://xtest.cnki.net', //灰度测试xtest
        // target: 'http://sso.dev.cnki.net/', //内网
        // target: 'https://gateway.cnki.net',//正式
        secure: true,
        changeOrigin: true,
        // 监听代理请求，添加自定义标头
        onProxyReq(proxyReq, req, res) {},
        onProxyRes(proxyRes, req, res) {},
      },
      {
        context: ['/member'],
        // target: 'http://member.dev.cnki.net:8089/', //内网
        target: "https://xms-api-test.cnki.net/", //xtest
        // target:'https://mxapi.cnki.net',//正式
        changeOrigin: true,
        onProxyRes(proxyRes, req, res) {
          if (proxyRes.headers['set-cookie']) {
            // accesstoken = proxyRes.headers['set-cookie'].join(';').split('AID=')[1].split(";")[0] 
            cookieMap[req.get('User-Agent')] = proxyRes.headers['set-cookie'].join(';')
            if (proxyRes.statusCode === 302) {
              res.redirect(openPage)
              return true
            }
          }
        },
      },
      {
        context: ['/personcentermember'],
        // target: 'http://member.dev.cnki.net/', //内网
        target: "https://xms-web-test.cnki.net/", //xtest
        // target:'https://mx.cnki.net',//正式
        pathRewrite: {
          '^/personcentermember': 'api'
        },
        changeOrigin: true,
        onProxyReq(proxyReq, req, res) {},
        onProxyRes(proxyRes, req, res) {},
      },
      {
        context: ['/RCDService'],
        target: "https://recsys.cnki.net/", //xtest
       
        changeOrigin: true,
        onProxyReq(proxyReq, req, res) {},
        onProxyRes(proxyRes, req, res) {},
      },

      {
        context: ['/file'],
        // target: 'https://gateway.cnki.net/hfs/',//正式
        // target: 'http://member.dev.cnki.net:8902/', //内网
        target: "https://gateway.cnki.net/hfs-test/", //xtest
       
        changeOrigin: true,
        onProxyReq(proxyReq, req, res) {},
        onProxyRes(proxyRes, req, res) {},
      },
      {
        context: ['/memberInfo','/activity'],
        // target: 'http://member.dev.cnki.net:8089/', //内网
        target: "https://xms-api-test.cnki.net/", //xtest
        // target:'https://mxapi.cnki.net',//正式
        changeOrigin: true,
        onProxyReq(proxyReq, req, res) {},
        onProxyRes(proxyRes, req, res) {},
      },
      {
        context: ['/consume'],
        // target: 'http://member.dev.cnki.net/', //内网
        target: "https://xms-web-test.cnki.net/", //xtest
        // target:'https://mx.cnki.net',//正式
        changeOrigin: true,
        onProxyReq(proxyReq, req, res) {},
        onProxyRes(proxyRes, req, res) {},
      },
      {
        context: ['/activity'],
        // target: 'http://member.dev.cnki.net/', //内网
        target: "https://xms-web-test.cnki.net/", //xtest
        // target:'https://mx.cnki.net',//正式
        changeOrigin: true,
        onProxyReq(proxyReq, req, res) {},
        onProxyRes(proxyRes, req, res) {},
      },
      {
        context: ['/wechat'],
        // target: 'http://member.dev.cnki.net/', //内网
        target: "https://xms-web-test.cnki.net/", //xtest
        // target:'http://x.cnki.net/',//正式
        changeOrigin: true,
        onProxyReq(proxyReq, req, res) {},
        onProxyRes(proxyRes, req, res) {},
      }
    ],

  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    // new HtmlWebpackPlugin({
    //   filename: 'winterMobile.html',
    //   template: path.resolve(intputDirectory + "/singlePage/", "index.html"),
    //   inject: true,
    //   chunks: ["winterMobile"],
    // }),
    // new HtmlWebpackPlugin({
    //   filename: 'winter.html',
    //   template: path.resolve(intputDirectory + "/index/", "index.html"),
    //   inject: true,
    //   chunks: ["vendor", "main"],
    // }),
  ].concat(htmlWebpackPlugins),
})